package com.codeoss.framework.webide.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.codeoss.framework.webide.request.DevWorkflowDesignerRequest;
import com.codeoss.framework.webide.response.DevWorkflowDesignerResponse;
import com.codeoss.framework.webide.service.IDevWorkflowDesignerService;

@Controller
@RequestMapping("devworkflowdesigner")
public class DevWorkflowDesignerController {
	@Autowired
	private IDevWorkflowDesignerService devWorkflowDesignerService;
	
	@RequestMapping(value = "init", method = RequestMethod.GET)
	@ResponseBody
	public DevWorkflowDesignerResponse init(@RequestParam("code")String code){
		DevWorkflowDesignerResponse devWorkflowDesignerResponse=devWorkflowDesignerService.init(code);
		return devWorkflowDesignerResponse;
	}
	
	@RequestMapping(value = "dataSave", method = RequestMethod.POST)
	@ResponseBody
	public DevWorkflowDesignerResponse dataSave(@RequestBody DevWorkflowDesignerRequest request){
		DevWorkflowDesignerResponse devWorkflowDesignerResponse=devWorkflowDesignerService.dataSave(request);
		return devWorkflowDesignerResponse;
	}
	
	@RequestMapping(value = "deploy", method = RequestMethod.POST)
	@ResponseBody
	public DevWorkflowDesignerResponse deploy(@RequestParam("code")String code){
		DevWorkflowDesignerResponse devWorkflowDesignerResponse=devWorkflowDesignerService.deploy(code);
		return devWorkflowDesignerResponse;
	}
	
	@RequestMapping(value = "dataExport", method = RequestMethod.GET)
	public void dataExport(@RequestParam("code")String code,HttpServletResponse response) throws IOException{
		DevWorkflowDesignerResponse devWorkflowDesignerResponse=devWorkflowDesignerService.dataExport(code);
		response.reset();
		try {
			response.addHeader("Content-Disposition","attachment;filename="+new String((devWorkflowDesignerResponse.getFileName()).getBytes(),"ISO-8859-1"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.getWriter().write(devWorkflowDesignerResponse.getFileContent());
	}
	
	@RequestMapping(value = "onTableSelectChangeHandler", method = RequestMethod.GET)
	@ResponseBody
	public DevWorkflowDesignerResponse onTableSelectChangeHandler(@RequestParam("irModelId")Long irModelId){
		DevWorkflowDesignerResponse devWorkflowDesignerResponse=devWorkflowDesignerService.onTableSelectChangeHandler(irModelId);
		return devWorkflowDesignerResponse;
	}
}
